package cn.school.controller.teacher.evaluation;

import cn.school.common.annotation.SysLog;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.enums.BusinessType;
import cn.school.common.utils.SysUserUtils;
import cn.school.sys.entity.AcademicYear;
import cn.school.sys.entity.TermTime;
import cn.school.sys.service.AcademicYearService;
import cn.school.sys.service.TermTimeService;
import cn.school.teacher.evaluation.dto.UserDto;
import cn.school.teacher.evaluation.entity.TeacherEvaluationTask;
import cn.school.teacher.evaluation.service.EvaluationTaskService;
import cn.school.teacher.evaluation.vo.MonthVo;
import cn.school.teacher.evaluation.vo.req.TeacherEvaluationTaskReqVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "ClassTeacherEvaluationTaskController => 考核任务管理）")
@RequestMapping("/teacher/evaluation/task")
public class EvaluationTaskController {

    @Autowired
    private EvaluationTaskService evaluationTaskService;
    @Autowired
    private AcademicYearService academicYearService;
    @Autowired
    private TermTimeService termTimeService;


    @ApiOperation("/list => 考核任务列表")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:list')")
    @GetMapping("/list")
    public CommonResult<CommonPage<TeacherEvaluationTask>> list(@RequestParam Map<String, Object> params) {
        IPage<TeacherEvaluationTask> page = this.evaluationTaskService.getPage(params);
        return CommonResult.success(CommonPage.restPage(page));
    }

    @ApiOperation("info/{id} => 获取考核任务")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:query')")
    @GetMapping("/info/{id}")
    public CommonResult<TeacherEvaluationTask> info(@PathVariable("id") Long id) {
        // 获取 task数据
        TeacherEvaluationTask entity = this.evaluationTaskService.getById(id);
        // 获取 task的打分用户
        if (entity != null) {
            // 受评人封装对象
            UserDto tetaCoverUser = this.evaluationTaskService.getTetaCoverUserByUserId(entity.getTetaCoverUserId());
            entity.setTetaCoverUser(tetaCoverUser);
            // 打分人封装对象
            List<UserDto> scoreUserList = this.evaluationTaskService.getSocreUserListByEvtaId(entity.getId());
            entity.setScoreUserList(scoreUserList);
        }

        if (entity == null) {
            return CommonResult.failed("该数据不存在，请刷新界面");
        }
        return CommonResult.success(entity);
    }

    @ApiOperation("update/{id} => 修改指定的考核任务")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:edit')")
    @SysLog(title = "修改指定考评方案", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update/{id}")
    public CommonResult<Integer> update(@PathVariable("id") Long id, @RequestBody TeacherEvaluationTask teacherEvaluationTask) {
        if (teacherEvaluationTask.getTetaType() != 0 &&  teacherEvaluationTask.getTetaType() != 1) {
            return CommonResult.failed();
        }
        int count = this.evaluationTaskService.update(id, teacherEvaluationTask);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("create => 新建考核任务")
    @PostMapping(value = "/create")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:add')")
    @SysLog(title = "新建考核任务", businessType = BusinessType.INSERT)
    public CommonResult<Integer> create(@RequestBody TeacherEvaluationTaskReqVo teacherEvaluationTaskVo) {
        if (teacherEvaluationTaskVo.getTetaType() != 0 && teacherEvaluationTaskVo.getTetaType() != 1) {
            return CommonResult.failed();
        }
        teacherEvaluationTaskVo.setUserId(SysUserUtils.getSysUser().getId());
        teacherEvaluationTaskVo.setTetaStatus(Short.valueOf("0"));
        int count = this.evaluationTaskService.create(teacherEvaluationTaskVo);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("deleteByIds/{ids} => 删除指定考核任务")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:remove')")
    @SysLog(title = "删除指定考核任务", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/deleteByIds/{ids}")
    public CommonResult<Integer> deleteByIds(@PathVariable Long[] ids) {
        int count = this.evaluationTaskService.deleteByIds(ids);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("/list/user => 受评人（班主任）查询")
//    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:list')")
    @GetMapping("/list/user")
    public CommonResult<CommonPage<UserDto>> listUser(@RequestParam Map<String, Object> params) {
        // 查询
        IPage<UserDto> page = this.evaluationTaskService.getPageByUser(params);
        return CommonResult.success(CommonPage.restPage(page));
    }


    @GetMapping("/list/userList")
    public CommonResult<CommonPage<UserDto>> listUserByName(@RequestParam Map<String, Object> params) {
        // 查询
        IPage<UserDto> page = this.evaluationTaskService.getPageByUserAndName(params);
        return CommonResult.success(CommonPage.restPage(page));
    }

    @ApiOperation("/list/academicYear => 学年查询")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:list')")
    @GetMapping("/list/academicYear")
    public CommonResult<List<AcademicYear>> listUcademicYear(@RequestParam Map<String, Object> params) {
        // 获取所有学年
        List<AcademicYear> list = this.academicYearService.getList(params);
        return CommonResult.success(list);
    }

    @ApiOperation("/list/termtime/{id} => 根据学年id，查询学年学期")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:list')")
    @GetMapping("/list/listTermtime/{id}")
    public CommonResult<List<TermTime>> listTermtime(@PathVariable Long id) {
        // 获取所有学年
        AcademicYear academicYear = this.academicYearService.getById(id);
        List<TermTime> list = this.termTimeService.getListByAcyeId(academicYear.getAcyeBeginYear(), academicYear.getAcyeEndYear());
        return CommonResult.success(list);
    }

    @ApiOperation("/list/listMonth/{id} => 根据学年id，查询所有的月份")
    @PreAuthorize("@ss.hasPermi('teacher:evaluation:task:list')")
    @GetMapping("/list/listMonth/{id}")
    public CommonResult<List<MonthVo>> listMonth(@PathVariable Long id) {
        // 获取所有学年
        AcademicYear academicYear = this.academicYearService.getById(id);
        List<TermTime> list = this.termTimeService.getListByAcyeId(academicYear.getAcyeBeginYear(), academicYear.getAcyeEndYear());
        List<MonthVo> monthList = new ArrayList<>();
        if (list != null && list.size() != 0) {
            MonthVo monthVo = null;
            int currentMonth = Calendar.getInstance().get(Calendar.YEAR) * 100 + Calendar.getInstance().get(Calendar.MONTH) + 1; // 当前时间对应的月份数(yyyyMM)
            for (TermTime termTime : list) {
                Calendar calendarBegin = Calendar.getInstance();
                calendarBegin.setTime(termTime.getTetiTermBeginDate());
                Calendar calendarEnd = Calendar.getInstance();
                calendarEnd.setTime(termTime.getTetiTermEndDate());

                // 计算结束月份 yyyyMM
                int endYear = calendarEnd.get(Calendar.YEAR) * 100;
                int endMonth = endYear + calendarEnd.get(Calendar.MONTH) + 1;
                for (; ; ) {
                    monthVo = new MonthVo();
                    // 计算当前(从开始时间开始，一个月一个月的递增)月份, yyyyMM
                    int beginYear = calendarBegin.get(Calendar.YEAR) * 100;
                    int beginMonth = beginYear + calendarBegin.get(Calendar.MONTH) + 1;
                    monthVo.setYearMonth(beginMonth);
                    // 当前月计算
                    if (currentMonth == beginMonth) {
                        monthVo.setCurrent(true); // 当前月份
                    }
                    monthList.add(monthVo);
                    // 后移一个月
                    calendarBegin.add(Calendar.MONTH, 1);
                    if (beginMonth == endMonth) {
                        break;
                    }
                }
            }
        }
        return CommonResult.success(monthList);
    }


}
